package com.jianganming.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import java.time.LocalDateTime;

public class WebSocketServer {
    public static void main(String[] args) {
        EventLoopGroup group1 = new NioEventLoopGroup(1);
        EventLoopGroup group2 = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            ChannelFuture future = bootstrap.group(group1, group2)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //http请求
                            pipeline.addLast(new HttpServerCodec());
                            //http请求数据分段处理
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            //路径
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello2"));
                            //TextWebSocketFrame 表示一个文本帧
                            pipeline.addLast(new SimpleChannelInboundHandler<TextWebSocketFrame>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
                                    System.out.println(msg.text());
                                    ctx.channel().writeAndFlush(new TextWebSocketFrame(LocalDateTime.now()+" "+msg.text()));
                                }
                            });
                        }
                    }).bind(7000).sync();

            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group1.shutdownGracefully();
            group2.shutdownGracefully();
        }
    }
}
